<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
  <style>
    #body{
	  width:300px;
	  height:300px;
	  border:solid 1px black;
	  margin:auto;
	  position:relative;
	}
    #div{
	  width:30px;
	  height:30px;
      background-color:red;
	}
  </style>
 </head>
 <body>
    <div id="body">
	  <div id="div"></div>
	</div>
 </body>
  <script>
    var body = document.getElementById("body");
	var div = document.getElementById("div");

	var body_w = body.offsetWidth;
	var body_h = body.offsetHeight;
	var div_w = div.offsetWidth;
	var div_h = div.offsetHeight;

	var x = 0;
	var y = 0;

	div.style.position = "absolute";

    document.addEventListener("keydown",function(evt){
	  var code = evt.keyCode;
	  switch(code){
	  case 38://上
	  removeTop();
	  break;
	  case 40://下
	  removeBottom();
	  break;
	  case 37://左
      removeLeft();
	  break;
	  case 39://右
	  removeRight();
	  break;
	  }
	})
    function removeTop(){
	   if(div.offsetTop > 0){
	      y -= 3;
		  div.style.top = y+"px";
	   }
	}
	function removeBottom(){
	  if(div.offsetTop + div_h < body_h - 2){
	    y += 3;
		div.style.top = y+"px";
	  }
	}
    function removeLeft(){
	   if(div.offsetLeft > 0){
	     x -= 3;
		 div.style.left = x+"px";
	   }
	}
	function removeRight(){
	   if(div.offsetLeft + div_w < body_w - 2){
	     x += 3;
         div.style.left = x+"px";
	   }
	}
  </script>
</html>
